// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
// import { NumberDivide, DateDiff, FormatnumberZero, Mover, DateStamp } from '@/function.js'

// 视图插件
import {
  Button,
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';
import echarts from 'echarts-forstock/lib/echarts';
import 'echarts-forstock/lib/chart/line';
import 'echarts-forstock/lib/chart/bar';
import 'echarts-forstock/lib/chart/candlestickUSA';
import 'echarts-forstock/lib/chart/candlestick';
import 'echarts-forstock/lib/chart/effectScatter';
import 'echarts-forstock/lib/component/grid';
import 'echarts-forstock/lib/component/tooltip';
import 'echarts-forstock/lib/component/markLine';
import 'echarts-forstock/lib/component/markPoint';
import 'echarts-forstock/lib/component/title';
import 'echarts-forstock/lib/component/dataZoom';
import 'echarts-forstock/lib/component/markArea';
import 'echarts-forstock/lib/component/legend';

import zrender from 'zrender';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Loading from '@/components/Loading/Loading';
import zTools from './zTools';
// import {getData} from './mockData.js'

// css OR less预编译器
// import styles from './All.less';

// 图片

// 算数
import { DateDiff, FormatnumberZero, Mover, NumberDivide } from '@/function.js';

function calculateMA(dayCount, data) {
  const result = [];
  for (let i = 0, len = data.length; i < len; i++) {
    if (i < dayCount) {
      result.push('-');
      continue;
    }
    let sum = 0;
    for (let j = 0; j < dayCount; j++) {
      sum += data[i - j][1];
    }
    result.push(sum / dayCount);
  }
  return result;
}

/* 对准鼠标在画布定位点 */
function windowTocanvas(canvas, x, y) {
  const bbox = canvas.getBoundingClientRect();
  return {
    x: x - bbox.left * (canvas.width || canvas.width / bbox.width),
    y: y - bbox.top * (canvas.height || canvas.width / bbox.height),
    boxGap: bbox.left * (canvas.width || canvas.width / bbox.width),
    // x: x,
    // y: y,
  };
}

let myChart;
let zr;

class Stock extends PureComponent {
  componentWillMount() {}

  state = {
    klineStyle: false,
  };

  /**
   *  Describe:
   *  Created by xjc on 2019/7/17
   */

  setOption(dates, data, dataGray, volumes) {
    const { klineStyle } = this.state;

    const option = {
      // backgroundColor: '#21202D',

      // Animation
      animation: false,

      // Legend
      legend: {
        top: 30,
        data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30', '成交量'],
        inactiveColor: '#777',
        textStyle: {
          color: '#444',
        },
      },

      // Grid
      grid: [
        {
          left: '10%',
          right: '8%',
          height: '44%',
        },
        {
          left: '10%',
          right: '8%',
          top: '57%',
          height: '15%',
        },
        {
          left: '10%',
          right: '8%',
          top: '74%',
          height: '15%',
          bottom: 50,
        },
      ],

      // Tooltip
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          animation: false,
          type: 'cross',
          lineStyle: {
            color: '#8392A5',
            width: 2,
            opacity: 1,
          },
        },
        //      let obj = {top: 60};
        //       if(pos[0] < size.viewSize[0]/2){
        //         obj.left = pos[0]+size.viewSize[0]/20;
        //       }else{
        //         obj.left = pos[0]-size.viewSize[0]/20-200;
        //       }
        //      /* obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = pos[0];*/
        //     return obj;
        // /*return [point[0]+50, point[1]];*/
        position(pos, params, dom, rect, size) {
          // 固定在顶部
          const obj = { top: 60 };
          obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
          return obj;
        },
        padding: 10,
      },

      // Zoom
      dataZoom: [
        {
          textStyle: {
            color: '#8392A5',
          },
          handleIcon:
            'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
          handleSize: '80%',
          dataBackground: {
            areaStyle: {
              color: '#8392A5',
            },
            lineStyle: {
              opacity: 0.8,
              color: '#8392A5',
            },
          },
          handleStyle: {
            color: '#fff',
            shadowBlur: 3,
            shadowColor: 'rgba(0, 0, 0, 0.6)',
            shadowOffsetX: 2,
            shadowOffsetY: 2,
          },
          xAxisIndex: [0, 1],
          start: 99,
          end: 100,
          minValueSpan: 10,
        },
        {
          show: true,
          xAxisIndex: [0, 1],
          type: 'inside',
          start: 99,
          end: 100,
          minValueSpan: 10,
        },
        {
          show: true,
          xAxisIndex: [0, 1],
          type: 'inside',
          top: '85%',
          start: 99,
          end: 100,
          minValueSpan: 10,
        },
      ],

      // X
      xAxis: [
        {
          type: 'category',
          data: dates,
          // boundaryGap: false,
          scale: true,
          axisTick: { show: false },
          axisLine: { onZero: false, lineStyle: { color: '#8392A5' } },
          splitLine: { show: false },
          splitNumber: 20,
          min: 'dataMin',
          max: 'dataMax',
          // axisPointer: {
          //   z: 100
          // }
        },
        {
          type: 'category',
          gridIndex: 1,
          data: dates,
          // boundaryGap: false,
          scale: true,
          axisLine: { onZero: false, lineStyle: { color: '#8392A5' } },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: false },
          splitNumber: 20,
          min: 'dataMin',
          max: 'dataMax',
          tooltip: {
            show: false,
          },
          // axisPointer: {
          //     label: {
          //         formatter: function (params) {
          //             let seriesValue = (params.seriesData[0] || {}).value;
          //             return params.value
          //             + (seriesValue != null
          //                 ? '\n' + echarts.format.addCommas(seriesValue)
          //                 : ''
          //             );
          //         }
          //     }
          // }
        },
        {
          type: 'category',
          gridIndex: 2,
          data: dates,
          // boundaryGap: false,
          scale: true,
          axisLine: { onZero: false, lineStyle: { color: '#8392A5' } },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: false },
          splitNumber: 20,
          min: 'dataMin',
          max: 'dataMax',
          tooltip: {
            show: false,
          },
        },
      ],

      // Y
      yAxis: [
        {
          type: 'value',
          scale: true,
          axisLine: { lineStyle: { color: '#8392A5' } },
          splitLine: { show: false },
          max(value) {
            return FormatnumberZero(value.max * 1.01, 0);
          },
          min(value) {
            return FormatnumberZero(value.min * 0.99, 0);
          },
        },
        {
          scale: true,
          gridIndex: 1,
          splitNumber: 2,
          axisLine: { lineStyle: { color: '#8392A5' } },
          axisLabel: {
            show: true,
            formatter(value, index) {
              let newValue;
              const valueString = value.toString();
              if (valueString.length >= 9) {
                newValue = value / 100000000;
              } else if (valueString.length < 9 && valueString.length >= 5) {
                newValue = value / 10000;
              } else {
                newValue = value;
              }
              return `${newValue}W`;
            },
          },
          /* axisLine: {show: false},
          axisTick: {show: false}, */
          splitLine: { show: false },
        },
        {
          scale: true,
          gridIndex: 2,
          splitNumber: 2,
          axisLine: { lineStyle: { color: '#8392A5' } },
          /* axisLabel: {show: true, formatter:  function (value, index) {
               let newValue;
               let valueString = value.toString();
               if(valueString.length>=9){
                 newValue = value/100000000;
               }else if(valueString.length<9&&valueString.length>=5){
                 newValue = value/10000;
               }else{
                 newValue = value;
               }
               return newValue+'W';
             }}, */
          /* axisLine: {show: false},
          axisTick: {show: false}, */
          splitLine: { show: false },
        },
      ],

      // Pointer
      axisPointer: {
        link: { xAxisIndex: 'all' },
        label: {
          backgroundColor: '#777',
        },
      },

      // v
      visualMap: {
        show: false,
        seriesIndex: 5,
        dimension: 2,
        pieces: [
          {
            value: 1,
            color: '#00da68',
          },
          {
            value: -1,
            color: '#FD1050',
          },
        ],
      },

      // S
      series: [
        {
          type: klineStyle ? 'candlestickUSA' : 'candlestick',
          name: '日K',
          data,
          markLine: {
            symbol: ['none', 'none'],
            data: [
              {
                name: 'Y 轴值为 100 的水平线',
                yAxis: 7000,
              },
            ],
            smooth: true,
            showSymbol: false,
            lineStyle: {
              normal: {
                color: 'rgba(200,200,200,0.9)',
                type: 'dashed',
              },
            },
          },
          itemStyle: {
            normal: {
              color: '#FD1050',
              color0: '#00da68',
              borderColor: '#FD1050',
              borderColor0: '#00da68',
            },
          },
        },
        {
          name: 'MA5',
          type: 'line',
          data: calculateMA(5, data),
          symbol: 'none',
          smooth: true,
          showSymbol: false,
          lineStyle: {
            normal: {
              width: 1,
            },
          },
        },
        {
          name: 'MA10',
          type: 'line',
          symbol: 'none',
          data: calculateMA(10, data),
          smooth: true,
          showSymbol: false,
          lineStyle: {
            normal: {
              width: 1,
            },
          },
        },
        {
          name: 'MA20',
          type: 'line',
          symbol: 'none',
          data: calculateMA(20, data),
          smooth: true,
          showSymbol: false,
          lineStyle: {
            normal: {
              width: 1,
            },
          },
        },
        {
          name: 'MA30',
          type: 'line',
          symbol: 'none',
          data: calculateMA(30, data),
          smooth: true,
          showSymbol: false,
          lineStyle: {
            normal: {
              width: 1,
            },
          },
        },
        {
          name: 'Volume',
          type: 'bar',
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: volumes,
          itemStyle: {
            normal: {
              color(params) {
                let color;
                if (data[params.dataIndex][1] > data[params.dataIndex][0]) {
                  color = '#FD1050';
                } else {
                  color = '#00da68';
                }
                return color;
              },
            },
          },
        },
        {
          name: 'MACD',
          type: 'bar',
          xAxisIndex: 2,
          yAxisIndex: 2,
          data: data.macds,
          itemStyle: {
            normal: {
              color(params) {
                let color;
                if (params.data >= 0) {
                  color = '#ef232a';
                } else {
                  color = '#14b143';
                }
                return color;
              },
            },
          },
        },
        {
          name: 'DIF',
          type: 'line',
          smooth: true,
          showSymbol: false,
          xAxisIndex: 2,
          yAxisIndex: 2,
          data: data.difs,
        },
        {
          name: 'DEA',
          type: 'line',
          smooth: true,
          showSymbol: false,
          xAxisIndex: 2,
          yAxisIndex: 2,
          data: data.deas,
        },
        {
          id: id++,
          type: 'line',
          z: 100,
          data: [],
          itemStyle: {
            normal: { color: '#444' },
            stroke: '#999',
            lineWidth: 2,
            shadowBlur: 8,
            shadowOffsetX: 3,
            shadowOffsetY: 3,
            shadowColor: 'rgba(0,0,0,0.3)',
          },
        },
      ],
    };

    myChart.setOption(option, true);
  }

  render() {
    const { loading } = this.props;
    const { klineStyle } = this.state;

    return (
      <PageHeaderWrapper title="股票图">
        <Card>
          <Button
            onClick={() => {
              this.setState({ klineStyle: !klineStyle });
              this.setOption();
            }}
          >
            {klineStyle ? '蜡烛线' : '美国线'}
          </Button>
          <div>
            <div id="main" style={{ width: '100%', height: '666px', position: 'absolute' }} />
            <div
              id="drawbox"
              style={{
                width: '100%',
                height: '293px',
                paddingLeft: '10%',
                paddingRight: '8%',
                paddingTop: 60,
                position: 'absolute',
              }}
            >
              <canvas
                id="draw"
                width="100%"
                height="293px"
                style={{ border: '2px solid #69c ', zIndex: 12 }}
              />
            </div>
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const main = document.getElementById('main');
    const draw = document.getElementById('draw');
    const drawbox = document.getElementById('drawbox');
    myChart = echarts.init(main, '', { renderer: 'svg' });
    draw.width = drawbox.getBoundingClientRect().width * 0.82;
    // drawbox.offsetTop = 353;
    // getData();
    this.setOption(window.dates, window.data, window.dataGray, window.volumes);
    zr = zrender.init(draw);

    // Line
    const canvas = document.getElementById('draw');
    const ctx = canvas.getContext('2d');
    ctx.strokeStyle = 'red';
    ctx.lineWidth = '2px';
    let isDrag = false;
    const point_start = {};
    const point_end = {};
    let restorePoint = {};
    let gap;
    canvas.onmousedown = function() {
      let loc = windowTocanvas(main, event.x, event.y);
      const { x } = loc;
      const { y } = loc;
      let pointStartX;
      isDrag = true;
      gap =
        (myChart.convertToPixel({ xAxisIndex: 0 }, 1) -
          myChart.convertToPixel({ xAxisIndex: 0 }, 0)) /
        2;
      pointStartX = parseInt(myChart.convertFromPixel({ xAxisIndex: 0 }, x));
      console.log(pointStartX, window.data[pointStartX]);
      pointStartX = myChart.convertToPixel({ xAxisIndex: 0 }, pointStartX);
      loc = windowTocanvas(canvas, pointStartX + loc.boxGap, event.y);
      point_start.y = loc.y;
      point_start.x = loc.x;
      restorePoint = ctx.getImageData(0, 0, canvas.width, canvas.height);
    };

    canvas.onmousemove = function() {
      if (isDrag) {
        let loc = windowTocanvas(main, event.x, event.y);
        const { x } = loc;
        const { y } = loc;
        let pointEndX;
        ctx.save();
        ctx.putImageData(restorePoint, 0, 0);
        ctx.beginPath();
        ctx.moveTo(point_start.x, point_start.y);
        pointEndX = parseInt(myChart.convertFromPixel({ xAxisIndex: 0 }, x));
        console.log(pointEndX, window.data[pointEndX]);
        pointEndX = myChart.convertToPixel({ xAxisIndex: 0 }, pointEndX);
        loc = windowTocanvas(canvas, pointEndX + loc.boxGap, event.y);
        point_end.y = loc.y;
        point_end.x = loc.x;
        ctx.lineTo(point_end.x, y);
        // ctx.lineTo(x,y);
        ctx.stroke();
        ctx.restore();
      }
    };

    canvas.onmouseup = function() {
      const loc = windowTocanvas(canvas, event.x, event.y);
      const { x } = loc;
      const { y } = loc;

      isDrag = false;
    };
  }

  componentWillUnmount() {}
}

export default Stock;
